<template>
  <div class="box">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-menu"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>附件管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="handle-box">
      <el-form ref="serch" :model="serch" :inline="true">
        <el-form-item>
          <el-input v-model="serch.fileName" size="small" placeholder="输入姓名检索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="small" @click="doSearch" plain round>搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-top: 20px;">
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :on-change="handleChange"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :file-list="myFileList"
        :before-upload="handleBefore"
        name="image"
        list-type="picture">
        <el-button type="danger" size="small" style="right:20px;width: 250px;float:right;position: fixed" round
                   icon="el-icon-upload"
                   plain>点击上传
        </el-button>
        <div slot="tip" style="right:10px;color: red;font-size:10px;margin-top:30px;width: 250px;float:right;position: fixed">文件不能超过3MB</div>
        <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
      </el-upload>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="page.pageNum"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes:="[10, 20, 30,40, 50,100]"
          :total="page.total">
        </el-pagination>
      </div>
      <el-dialog :visible.sync="dialogVisible" size="tiny" top="10px">
        <img width="100%" :src="dialogImageUrl" alt="图片预览">
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {Loading} from 'element-ui'
  import common from '../../../common/constant.js'
  import ElCol from "element-ui/packages/col/src/col";
  export default{
    components: {ElCol},
    data(){
      const current = 1
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        serch: {
          fileName: '',
          fileType: '',
          businessType: ''
        },
        uploadUrl: common.homeUrl + '/upload',
        ruleForm: [],
        myFileList: [],
        attachment: {
          id: 0,
          type: 0,
          relation: 0
        },
        page: {
          pageNum: 1,
          pageSize: 15,
          size: 2,
          orderBy: null,
          startRow: 3,
          endRow: 4,
          total: 4,
          pages: 2,
          list: [],
          firstPage: 1,
          prePage: 1,
          nextPage: 0,
          lastPage: 2,
          isFirstPage: false,
          isLastPage: true,
          hasPreviousPage: true,
          hasNextPage: false,
          navigatePages: 8,
          navigatepageNums: [
            1,
            2
          ]
        },
        currentPageNum: current,
        imageShow: false,
        confirmDialog: false,
        removeFile: []
      }
    },
    created: function () {
      this.queryFileList()
    },
    methods: {
      handleSizeChange(value){
        this.page.pageSize = value
        this.query()
      },
      handleCurrentChange(val) {
        let self = this
        self.page.currentPage = val
        self.query()
      },
      uploadFile(){
        console.log('上传附件')
      },
      doSearch(){
        console.log('搜索一下')
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handleBefore(file) {
        // 限制图片大小不超过500KB
        /*const isJPG = file.type === 'image/jpeg'
         const isPNG = file.type === 'image/png'
         if (!isJPG&&!isPNG) {
         this.$notify.error({
         title: '警告',
         message: '只支持上传png/jpg图片！',
         duration: 0
         });
         return false
         }*/
        const oneMB = 1048576
        let fileSize = file.size;
        if (fileSize > 3 * oneMB) {
          this.$notify.error({
            title: '警告',
            message: '图片大小不能超过3MB，当前图片大小:' + Math.round(fileSize / oneMB) + 'MB',
            duration: 0
          });
          return false
        }
        return true
      },
      handleRemove(file, fileList) {
        let self = this
        this.$confirm('图片删除后不可恢复，确定删除该图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          let loadingInstance = Loading.service({
            fullscreen: true,
            text: "操作中......"
          })
          self.$http.post('/api/upload/delete', {
            'id': file.id,
            'filename': file.name
          })
            .then((response) => {
              let responseData = response.data
              if (responseData.flag === common.respons.seccuss) {
                this.queryFileList()
              } else {
                this.$notify.error({
                  title: '错误',
                  message: '查询失败！',
                  duration: 6000
                })
              }
              loadingInstance.close()
            })
            .catch(function (response) {
              loadingInstance.close()
              this.message_error()
              console.log(response)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
          this.queryFileList()
        });
      },
      handlePreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleSuccess(response, file, fileList){
        if (response.flag === common.respons.seccuss) {
          this.myFileList.push(file)
        } else {
          this.message_error('上传图片失败！')
        }
      },
      handleError(err, file, fileList) {
        console.log(err, file, fileList)
      },
      handleChange(file, fileList) {

      },
      queryFileList() {
        let self = this
        let loadingInstance = Loading.service({
          fullscreen: true,
          text: "操作中......"
        })
        self.$http.post('/api/attachment', {
          'business': self.fileName,
          'pageSize': self.page.pageSize,
          'pageNum': self.page.pageNum
        })
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.myFileList = []
              self.page = responseData.pageData
              let list = responseData.pageData.list
              for (var i = 0; i < list.length; i++) {
                let image = {'name': list[i].filename, 'url': list[i].filepath, 'id': list[i].id}
                self.myFileList.push(image)
              }
            } else {
              this.$notify.error({
                title: '错误',
                message: '查询失败！',
                duration: 6000
              })
            }
            loadingInstance.close()
          })
          .catch(function (response) {
            loadingInstance.close()
            this.message_error()
            console.log(response)
          })
      },
      message_error(message) {
        if (message === null) {
          this.$notify.error({
            title: '错误',
            message: '操作失败'
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: message
          });
        }
      },
      message_ok(message) {
        if (message === null) {
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success'
          });
        } else {
          this.$notify({
            title: '成功',
            message: message,
            type: 'success'
          });
        }

      }
    }
  }
</script>

<style scoped>

</style>
